package com.gdpu.service.impl;

import com.gdpu.api.CommonPage;
import com.gdpu.config.RedisConfig;
import com.gdpu.dto.PmsGoodDto;
import com.gdpu.mapper.PmsGoodsMapper;
import com.gdpu.model.PmsGoods;
import com.gdpu.model.PmsGoodsExample;
import com.gdpu.service.PmsGoodsService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @Author:weiming
 * @Date:2021/5/27
 */
@Service
public class PmsGoodServiceImpl implements PmsGoodsService{
    @Autowired
    private PmsGoodsMapper pmsGoodsMapper;

    @Override
    public CommonPage list(Integer pageNum, Integer pageSize) {
        Page<Object> page = PageHelper.startPage(pageNum, pageSize);
        PmsGoodsExample pmsGoodsExample = new PmsGoodsExample();
        PmsGoodsExample.Criteria criteria = pmsGoodsExample.createCriteria();
        pmsGoodsExample.setOrderByClause("sort desc");
        criteria.andIsDeletedEqualTo(0);
        List<PmsGoods> pmsGoodsList = pmsGoodsMapper.selectByExample(pmsGoodsExample);
        return CommonPage.restPage(pmsGoodsList, page);
    }

    @Override
    public PmsGoods get(Integer id) {
            PmsGoods pmsGoods = pmsGoodsMapper.selectByPrimaryKey(id);
            return pmsGoods;
    }

    @Override
    public int add(PmsGoodDto pmsGoodDto) {
        PmsGoods pmsGoods = new PmsGoods();
        BeanUtils.copyProperties(pmsGoodDto,pmsGoods);
        pmsGoods.setCreateTime(new Date());
        pmsGoods.setGoodStock(0);
        pmsGoods.setSaleNum(0);
        pmsGoods.setId(null);
        pmsGoods.setCost(new BigDecimal("0"));
        int count = pmsGoodsMapper.insert(pmsGoods);
        return count;
    }

    @Override
    @CacheEvict(value = RedisConfig.REDIS_KEY_DATABASE,key = "'pms:good:'+#id")
    public int delete(Integer id) {
        PmsGoods pmsGoods = new PmsGoods();
        pmsGoods.setId(id);
        pmsGoods.setIsDeleted(1);
        pmsGoods.setIsSale(0);
        int count = pmsGoodsMapper.updateByPrimaryKeySelective(pmsGoods);
        return count;
    }

    @Override
    @CacheEvict(value = RedisConfig.REDIS_KEY_DATABASE,key = "'pms:good:'+#pmsGoodDto.id")
    public int update(PmsGoodDto pmsGoodDto) {
        PmsGoods pmsGoods = new PmsGoods();
        BeanUtils.copyProperties(pmsGoodDto,pmsGoods);
        int count = pmsGoodsMapper.updateByPrimaryKeySelective(pmsGoods);
        return count;
    }
}
